package com.jiankangjin.weixinchannel.config;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.jiankangjin.common.json.fastjson.JSONUtil;
import com.jiankangjin.common.lang.StringUtils;
import com.jiankangjin.weixinchannel.util.TenpayHttpClient;

/**
 * 商户配置
 */
public class WeixinConfig {
	private static final transient Log logger = LogFactory.getLog(WeixinConfig.class);
	
	/** 商户  */
	public static String PARTNER_ID			= null; //"1220586901";
	/** 商户 私钥  */
	public static String PARTNER_KEY 		= null; //"5cc920216e174c9289d634fc6bf2530b";
	/** 商户   */
	public static String APP_ID 			= null; //"wxcec8863ae602c67c";
	/** 微信支付商户号   */
	public static String MCH_ID 			= null; //"10017474";
	/** API权限Key   */
	public static String APP_SECRET 		= null; //"701f0114d3ee3ebf972f162bafbc42f9";
	/** 商户   */
	public static String APP_KEY 			= null; //"c8tMWlRG2GD3luoBn10wqx6DRuphLYulIhqcgp1BdRqM87m49bWMsHVAYTAXrioVScRFntk5Xdy6QYBnKYCWJsOwiWrCkBdJoINXJTbs9LEnkHBvkyuuYxO1XRfTZgEB";
	/** 接收微信订单通知的地址  */
	public static String NOTIFY_URL 		= null; //"http://payment-test.jiankangjin.com/weixinChannel/notify";
	/** token过期时间  */
	public static String TOKEN_GET_PERIOD	= null; //"6000000";
	/** 微信API地址-token  */
	public static String TOKEN_URL			= null; //"https://api.weixin.qq.com/cgi-bin/token";
	/** 微信API地址-发货  */
	public static String DELIVER_NOTIFY_URL	= null; //"https://api.weixin.qq.com/pay/delivernotify?access_token=";
	/** 微信API地址-订单查询  */
	public static String ORDER_QUERY_URL	= null; //"https://api.weixin.qq.com/pay/orderquery?access_token=";
	
	/** 当前token串  */
	private static String accessToken;
	
	/** token最后时间  */
	private static long lastTokenGetTime;
	
	static {
		//加载配置文件
		try {
			Properties props = PropertiesLoaderUtils.loadAllProperties("wx_config.properties");
			WeixinConfig.PARTNER_ID = props.getProperty("PARTNER_ID");
			WeixinConfig.PARTNER_KEY = props.getProperty("PARTNER_KEY");
			WeixinConfig.APP_ID = props.getProperty("APP_ID");
			WeixinConfig.MCH_ID = props.getProperty("MCH_ID");
			WeixinConfig.APP_SECRET = props.getProperty("APP_SECRET");
			WeixinConfig.APP_KEY = props.getProperty("APP_KEY");
			WeixinConfig.NOTIFY_URL = props.getProperty("NOTIFY_URL");
			WeixinConfig.TOKEN_GET_PERIOD = props.getProperty("TOKEN_GET_PERIOD");
			WeixinConfig.TOKEN_URL = props.getProperty("TOKEN_URL");
			WeixinConfig.DELIVER_NOTIFY_URL = props.getProperty("DELIVER_NOTIFY_URL");
			WeixinConfig.ORDER_QUERY_URL = props.getProperty("ORDER_QUERY_URL");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			logger.error("wx_config.properties文件未找到！");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("加载wx_config.properties文件失败！");
		}
	}
	public static String getAccessToken(){
		if(needGetToken()){
			accessToken = WeixinConfig.getAccessTokenFromWX();
			lastTokenGetTime = System.currentTimeMillis();
		}
		return accessToken;
	}
	
	/**
	 * 根据最后时间更新当前token串
	 */
	private static boolean needGetToken(){
		long currentTime = System.currentTimeMillis();
		if(lastTokenGetTime==0){
			logger.info("首次获取ACCESS_TOKEN");
			return true;
		}
		long tokenGetPeriod = Long.parseLong(WeixinConfig.TOKEN_GET_PERIOD);
		if(currentTime-lastTokenGetTime>tokenGetPeriod){
			logger.info("需要再次获取ACCESS_TOKEN");
			return true;
		}
		logger.info("无需获取ACCESS_TOKEN");
		return false;
	}
	
	/*
	 * 获得token
	 */
	private static String getAccessTokenFromWX(){
		String url = WeixinConfig.TOKEN_URL;
//		Map<String, Object> params = new HashMap<String, Object>();
//        params.put("grant_type", "client_credential");
//        params.put("appid", WeixinConfigAPP_ID"));
//        params.put("secret", WeixinConfigAPP_SECRET"));
//        logger.info("获取微信渠道ACCESS_TOKEN请求参数："+params.toString());
		url += "?grant_type=client_credential&appid="+WeixinConfig.APP_ID
				+"&secret="+WeixinConfig.APP_SECRET;
		
        TenpayHttpClient httpClient = new TenpayHttpClient();
		boolean resultFlag = httpClient.callHttpPost(url, "");
		if(!resultFlag){
			logger.info("获取微信ACCESS_TOKEN失败！");
			return null;
		}
		
        //提取access_token
		@SuppressWarnings("unchecked")
		Map<String,String> map = (Map<String,String>)JSONUtil.fromJSON(httpClient.getResContent());
		String accessToken = map.get("access_token");
		if(StringUtils.isEmpty(accessToken)){
			logger.info("获取ACCESS_TOKEN失败！"+httpClient.getResContent());
			return null;
		}
		logger.info("获取ACCESS_TOKEN成功！ACCESS_TOKEN=["+accessToken+"]");
		return accessToken;
	}
	
}

